import store from '@/common/store';

export default {
	config: {
		baseUrl: store.state.apiBaseUrl,
		headers: {"content-type":"application/x-www-form-urlencoded"},
		dataType: "json",
		responseType: "text"
	},
	interceptor: {
		request:function(_config){
		},
		response: null
	},
	request(options) {
		return new Promise((resolve, reject) => {
			let _config = null
			options.url = this.config.baseUrl + options.url
			// if(uni.getStorageSync('token')){
			// 	options.data.access_token = uni.getStorageSync('token')
			// }
			// uni.setStorageSync("token","TfMVCotnN_70mixk0Ew0jC5M7izNIfQu_1570614699")
			options.data.openId = uni.getStorageSync(store.state.tokenName)
			options.complete = (response) => {
				response.config = _config
				if (this.interceptor.response) {
					response = this.interceptor.response(response)
				}
				else if (response.statusCode === 200) { //成功
				// if(response.data&&response.data.data.code == 426){
				// 		uni.setStorageSync("backurl",location.hash.substr(1,location.hash.length))
				// 		// location.href=store.state.BaseUrl+"/index_login.html"
				// }
					resolve(response.data);
				} else {
					reject(response)
				}
			}

			_config = Object.assign({}, this.config, options)
			_config.requestId = new Date().getTime()
			
			if (this.interceptor.request) {
				this.interceptor.request(_config)
			}
			
			uni.request(_config);
		});
	},
	get(url, data, options) {
		data = data?data:{};
		
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	},
	post(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	},
	put(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'PUT'
		return this.request(options)
	},
	del(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	}
}